package org.chz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.var;
import org.chz.entity.WebPage;
import org.chz.service.KeyRecommendService;
import org.chz.service.WebSearchService;
import org.chz.system.CandidateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.PriorityQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Controller
public class SearchEnginController {

    @Autowired
    KeyRecommendService keyRecommendService;
    @Autowired
    WebSearchService webSearchService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(value = "/suggest", method = RequestMethod.GET)
    @ResponseBody
    public String suggest(@RequestParam(required = false, defaultValue = "") String word)
            throws JsonProcessingException, ExecutionException, InterruptedException {

        var ret = redisTemplate.opsForValue().get(word);
        if(ret == null){
            Collection<CandidateResult> keywords = keyRecommendService.doQuery(word).get();
            redisTemplate.opsForValue().set(word, keywords);
            System.out.println("未命中");
            return objectMapper.writeValueAsString(keywords);
        }
        System.out.println("命中");
        return objectMapper.writeValueAsString(ret);
    }


    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public CompletableFuture<Collection<WebPage>> search(@RequestParam(required = false, defaultValue = "") String sentence) {
        return webSearchService.doQuery(sentence);
    }
}
